#!/bin/bash

set -e

[[ ! -n "$GATEWAY" || ! -n "$SECRUE" || ! -n "$GROUP" || ! -n "$USER" || ! -n "$PASSWORD" ]] && echo "required parameter missing" && exit 0

function connect() {
    opt_passwd=`oathtool  --totp --base32 $SECRUE`
    if [[ $GATEWAY =~ ^[a-z\|A-Z] ]];then
        openconnect  $GATEWAY   --authgroup=$GROUP  --user=$USER  --no-dtls  -b   <<EOF
$opt_passwd
$PASSWORD
EOF
    else
        openconnect  $GATEWAY   --authgroup=$GROUP  --user=$USER  --no-dtls  -b   <<EOF
yes
$opt_passwd
$PASSWORD
EOF
    fi
}

iptables -A FORWARD -i tun0 -j ACCEPT; iptables -A FORWARD -o tun0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE; iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE

while true ; do
    [[ -z "$(ps -aux | grep openconnect |grep -v grep)" ]]  && echo `date "+%Y-%m-%d %H:%M:%S" `  重新拉起vpn进程 && connect
    sleep 150
done
